#! /usr/bin/env python

import os
import fcntl

class Lock:
    def __init__(self, location, name):
        self.lf = open(os.path.join(location, '%s%s' % (name, '.lock')), 'w')

    def lock(self):
        fcntl.lockf(self.lf, fcntl.LOCK_EX)

    def unlock(self):
        fcntl.lockf(self.lf, fcntl.LOCK_UN)

    def __del__(self):
        self.lf.close()

if __name__ == '__main__':
    import time
    def try_lock(suit, lock):
        print '%s: try to lock' % suit
        lock.lock()
        print '%s: lock success' % suit
        time.sleep(5)
        lock.unlock()
        print '%s: unlock success' % suit

    lock = Lock('.', 'lock')

    pid = os.fork()
    if pid == 0:
        try_lock('child', lock)
    else:
        try_lock('father', lock)

    del lock
